<?php
declare (strict_types=1);

namespace app\admin\controller;

use addons\BuilderPlus\components\Button;
use addons\BuilderPlus\components\Column as Col;
use addons\BuilderPlus\components\Edit;
use addons\BuilderPlus\components\Search;
use addons\BuilderPlus\facade\Table;
use think\facade\View;

class Role extends Base
{

    public function getOptions(): array
    {
        return [
            'pk'    => 'id',
            'model' => \app\common\model\Role::class
        ];
    }

    public function index(): string
    {
        return Table::init($this)
            ->setCheckbox(false)
            ->addColumns([
                ['id', 'ID', fn(Col $col) => $col->width(80)],
                ['title', '角色名', null, fn(Edit $e) => $e->require()],
                ['explain', '角色说明', null, fn(Edit $e) => $e->require()],
                ['create_time', '添加时间', fn(Col $col) => $col->width(140)],
                ['status', '状态', fn(Col $col) => $col->switch('开启|关闭', '1|0')->fixed('right')]
            ])
            ->addTopButtons(['add'])
            ->addRightButtons([
                'edit',
                'give' => fn(Button $b) => $b->title('分配权限')->event('od')->url(url('role/give')->build()),
                'delete'
            ], 200)
            ->addSearch([
                ['title', '角色名筛选', fn(Search $search) => $search->condition('Like')],
                ['create_time', '添加时间', fn(Search $search) => $search->type('date')]
            ])
            ->specifyQuery([['id', '>', 1]])
            ->fetch();

    }

    public function give()
    {
        if ($this->request->isPost()) {
            try {
                $param = $this->request->post();
                $param['rules'] = $param['rules'] ? implode(',', $param['rules']) : '';
                $this->model::update($param);
                return json(['code' => 1, 'msg' => '操作成功']);
            } catch (\Exception $e) {
                return json(['code' => -1, 'msg' => $e->getMessage()]);
            }
        }

        extract((new \app\common\model\Menu())->getAuth($this->request->get('id')));

        function childrenFun($item, $rule)
        {
            $children = [];
            foreach ($item['child'] as $child) {
                $children[] = [
                    'id'       => $child['id'],
                    'title'    => $child['title'],
                    'spread'   => true,
                    'children' => childrenFun($child, $rule),
                    'checked'  => in_array($child['id'], $rule)
                ];
            }
            return $children;
        }

        $list = [];
        foreach ($menu as $item) {
            $data = [
                'id'       => $item['id'],
                'title'    => $item['title'],
                'spread'   => true,
                'children' => childrenFun($item, $rule),
            ];
            $list[] = $data;
        }
        return View::assign('list', $list)->fetch();
    }
}
